import { Steps } from 'antd'
import { ImportantEditModal } from '@/desktop/components'
import type { CodeRule, BaseCodeRule } from '@/services/features/code-join-groups'
import { getEmptyBaseCodeRule } from '@/services/features/code-join-groups'

import './index.module.less'
import ChooseGroups from './ChooseGroups'
import ChooseQywxs from './ChooseQywxs'
import EditRule from './EditRule'

export interface EditingRule extends BaseCodeRule {
  id?: number
}

export default function RuleEditModal(props: {
  editing: false | true | CodeRule
  onFinish: () => void
}) {
  const { editing, onFinish } = props

  const title = editing !== false ? (editing === true ? '新建规则' : '编辑规则') : ''

  return <ImportantEditModal
    title={title}
    width="900px"
    styleName="modal"
    open={editing !== false}
    onCancel={onFinish}
  >
    {editing !== false ? <Content editing={editing} onFinish={onFinish} /> : null}
  </ImportantEditModal>
}

enum EditSteps {
  ChooseQywxs = 0,
  ChooseGroups = 1,
  Config = 2,
}

function Content(props: { editing: true | CodeRule; onFinish: () => void }) {
  const { editing, onFinish } = props

  const [step, setStep] = useState(EditSteps.ChooseQywxs)
  const [rule, setRule] = useState<EditingRule>(() =>
    editing === true ? getEmptyBaseCodeRule() : editing,
  )
  const prevStep = useCallback(
    (editingRule?: Partial<EditingRule>) => {
      if (editingRule) setRule({ ...rule, ...editingRule })
      if (step !== EditSteps.ChooseQywxs) setStep(step - 1)
    },
    [step, rule],
  )

  const choosedQywxs = useCallback(
    (wxids: string[]) => {
      setRule({ ...rule, wxids })
      setStep(EditSteps.ChooseGroups)
    },
    [rule],
  )

  const choosedGroups = useCallback(
    (updates: Partial<EditingRule>) => {
      setRule({ ...rule, ...updates })
      setStep(EditSteps.Config)
    },
    [rule],
  )

  return <>
    <div styleName="steps-wrap">
      <Steps current={step}>
        <Steps.Step title="选择企微账号" />
        <Steps.Step title="进群设置" />
        <Steps.Step title="口令设置" />
      </Steps>
    </div>

    {step === EditSteps.ChooseQywxs ? (
      <ChooseQywxs wxids={rule.wxids} choosed={choosedQywxs} />
    ) : null}
    {step === EditSteps.ChooseGroups ? (
      <ChooseGroups rule={rule} goPrev={prevStep} choosed={choosedGroups} />
    ) : null}
    {step === EditSteps.Config ? (
      <EditRule rule={rule} goPrev={prevStep} onFinish={onFinish} />
    ) : null}
  </>
}
